﻿using UnityEngine;
using System.Collections;

public class InputController : MonoBehaviour
{
	public enum Direction { Left, Right, Up, Down }

	public float moveSpeed = 10f;

	public float zoom;
	public float zoomTarget;
	public float zoomSpeed = 100f;
	public float zoomLerpSpeed = 16f;
	public float minZoom = 0.1f;

	public Vector3 worldMousePosition;
	public float gridSize = 0.01f;

	// Use this for initialization
	void Start()
	{
		worldMousePosition = UnityUtils.ScreenPointToWorldXY( Input.mousePosition );
		worldMousePosition = MathUtils.SnapPointToGrid( worldMousePosition, gridSize );

		zoom =
		zoomTarget = Mathf.Abs( transform.position.z );
	}

	// Update is called once per frame
	void Update()
	{
		worldMousePosition = UnityUtils.ScreenPointToWorldXY( Input.mousePosition );
		worldMousePosition = MathUtils.SnapPointToGrid( worldMousePosition, gridSize );

		float dt = Time.deltaTime;

		float zaxis = Input.GetAxis( "Mouse ScrollWheel" );
		zoomTarget *= ( 1f - zaxis * zoomSpeed * dt );
		if ( zoomTarget < minZoom )
			zoomTarget = minZoom;
		zoom = Mathf.Lerp( zoom, zoomTarget, zoomLerpSpeed * dt );

		Vector3 pos = transform.localPosition;

		pos.x += Input.GetAxis( "Horizontal" ) * moveSpeed * dt;
		pos.y += Input.GetAxis( "Vertical" ) * moveSpeed * dt;
		pos.z = -zoom;

		transform.localPosition = pos;

		if ( Input.GetKeyDown( KeyCode.Escape ) )
			Application.Quit();

		MoveByKey( KeyCode.LeftArrow, new Vector3( -moveSpeed, 0f ), dt );
		MoveByKey( KeyCode.UpArrow, new Vector3( 0f, moveSpeed ), dt );
		MoveByKey( KeyCode.RightArrow, new Vector3( moveSpeed, 0f ), dt );
		MoveByKey( KeyCode.DownArrow, new Vector3( 0f, -moveSpeed ), dt );
	}

	void MoveByKey( KeyCode k, Vector3 velocity, float dt )
	{
		if ( Input.GetKeyDown( k ) )
			transform.localPosition += velocity * dt;
	}
}
